<script setup lang="ts">
  import { PropType, watch, ref } from "vue";
  import { ElForm, ElFormItem, FormInstance } from "element-plus";
  import StockSelect from "./StockSelect.vue";
  const
    props = defineProps({
      modelValue: { type: Object as PropType<gt.sql.order>, default: format.def.order, },
      curd: { type: Number as PropType<gt.curd>, default: 2 }
    }),
    stockSelect = ref<InstanceType<typeof StockSelect>>(),
    rules = ref({
      name: { required: true, message: "请填写标题", trigger: "blur", min: 1 },
      type: { required: true, message: "请选择商品类型", trigger: "blur", min: 1 },
    }),
    entity = ref<FormInstance>();

  async function init() {

  }
  function addOut() {
    stockSelect.value?.open().then(async (p) => {
      if (p) {
        props.modelValue.content.out.push(await format.stockLog({
          stock: p.id,
          max: p.sum
        }));
      }
    });
  }
  function addIn() {
    stockSelect.value?.open().then(async (p) => {
      if (p) {
        props.modelValue.content.in.push(await format.stockLog({
          stock: p.id,
          max: p.sum
        }));
      }
    });
  }

  watch(() => props.modelValue, init, { deep: true, immediate: true });

  defineExpose({
    validate() {
      return new Promise<boolean>(async (resolve) => {
        if (!props.curd) {
          const { content } = props.modelValue,
            ogs: { [k: string]: number; } = {};
          for (let i = 0; i < content.out.length; i++) {
            const e = content.out[i];
            if (!e.stock) {
              ElMessageBox.confirm(`出库详情第[${i + 1}]行未选择库存`, "错误", { type: "error", });
              return resolve(false);
            }
            const goods = e._stock?.goods || "";
            if (!ogs[goods]) {
              ogs[goods] = 0;
            }
            if (e.sum === undefined || !(e.sum > 0)) {
              e.sum = 0;
            }
            ogs[goods] += e.sum;
          }
          for (let i = 0; i < content.in.length; i++) {
            const e = content.in[i];
            if (!e.stock) {
              ElMessageBox.confirm(`入库详情第[${i + 1}]行未选择库存`, "错误", { type: "error", });
              return resolve(false);
            }
            if (!e.sum || e.sum < 0) { e.sum = 0; }
            const goods = e._stock?.goods || "";
            if (!ogs[goods]) {
              ElMessageBox.confirm(`入库详情第[${i + 1}]行 出库不足`, "错误", { type: "error", });
              return resolve(false);
            }
            ogs[goods] -= e.sum;
            if (ogs[goods] < 0) {
              ElMessageBox.confirm(`入库详情第[${i + 1}]行 出库数不足`, "错误", { type: "error", });
              return resolve(false);
            }
          }
          try {
            Object.keys(ogs).forEach(k => {
              if (ogs[k] < 0) {
                const i = content.out.findIndex(e => e.stock == k);
                ElMessageBox.confirm(`出库详情第[${i + 1}]行 小于入库数量;`, "错误", { type: "error", });
                throw null;
              } else if (ogs[k] > 0) {
                const i = content.out.findIndex(e => e.stock == k);
                ElMessageBox.confirm(`出库详情第[${i + 1}]行 大于入库数量;`, "错误", { type: "error", });
                throw null;
              }
            });
          } catch (_) {
            return resolve(false);
          }
        }

        if (entity.value) {
          entity.value.validate().then(resolve).catch(() => { resolve(false); });
        } else {
          resolve(false);
        }
      });
    },
    resetFields() { entity.value?.resetFields(); }
  });
</script>
<template>
  <ElForm class="order xw zb" ref="entity" :model="modelValue" :rules="rules" labelWidth="7em">
    <ElFormItem label="id" prop="id">
      <el-input v-model="modelValue.id" disabled placeholder="系统自动生成" />
    </ElFormItem>
    <ElFormItem label="创建时间" prop="createTime">
      <el-input :modelValue="modelValue.createTime ? modelValue._createTime : '系统自动生成'" disabled />
    </ElFormItem>
    <ElFormItem label="支付时间" prop="createTime">
      <el-input :modelValue="modelValue.payTime ? modelValue._payTime : '未支付'" disabled />
    </ElFormItem>
    <ElFormItem label="操作人" prop="_user.name">
      <el-input :modelValue="modelValue._user?.name" placeholder="系统自动生成" disabled />
    </ElFormItem>
    <ElFormItem label="标题" prop="name">
      <el-input v-model="modelValue.name" placeholder="请输入名称" :disabled="curd == 2" />
    </ElFormItem>
    <ElFormItem label="备注" prop="des" class="wf">
      <el-input v-model="modelValue.des" placeholder="请输入备注" :disabled="curd == 2" />
    </ElFormItem>
    <ElFormItem class="wf" label="出库详情" prop="banner">
      <template #label>
        <div class="whf y je">
          <div class="el-form-item__label">出库详情</div>
          <el-button type="primary" class="mt1em" @click="addOut" :disabled="!!curd">新增</el-button>
        </div>
      </template>
      <el-table stripe highlight-current-row :data="modelValue.content.out" class="wf ox" height="15em" type="expand"
        row-key="id">
        <el-table-column prop="_stock._group.name" label="库存" width="100" show-overflow-tooltip />
        <el-table-column prop="_stock._goods.name" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="_stock._goods.money" label="单价" show-overflow-tooltip />
        <el-table-column prop="sum" label="数量" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input-number class="wf" v-model="row.sum" :min="!!curd ? undefined : 0" :max="row._stock.sum"
              :disabled="!!curd" />
          </template>
        </el-table-column>
        <el-table-column prop="sum" label="备注" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input class="wf" v-model="row.des" :disabled="!!curd" />
          </template>
        </el-table-column>
        <el-table-column prop="_createTime" label="创建时间" width="120" show-overflow-tooltip />
        <el-table-column prop="_user.name" label="创建人" width="100" show-overflow-tooltip />
      </el-table>
    </ElFormItem>
    <ElFormItem class="wf" label="入库详情" prop="banner">
      <template #label>
        <div class="whf y je">
          <div class="el-form-item__label">入库详情</div>
          <el-button type="primary" class="mt1em" @click="addIn" :disabled="!!curd">新增</el-button>
        </div>
      </template>
      <el-table stripe highlight-current-row :data="modelValue.content.in" class="wf" height="15em" type="expand"
        row-key="id">
        <el-table-column prop="_stock._group.name" label="库存" width="100" show-overflow-tooltip />
        <el-table-column prop="_stock._goods.name" label="商品名称" show-overflow-tooltip />
        <el-table-column prop="_stock._goods.money" label="单价" show-overflow-tooltip />
        <el-table-column prop="sum" label="数量" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input-number class="wf" v-model="row.sum" :min="!!curd ? undefined : 0" :disabled="!!curd" />
          </template>
        </el-table-column>
        <el-table-column prop="sum" label="备注" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-input class="wf" v-model="row.des" :disabled="!!curd" />
          </template>
        </el-table-column>
        <el-table-column prop="_createTime" label="创建时间" width="120" show-overflow-tooltip />
        <el-table-column prop="_user.name" label="创建人" width="100" show-overflow-tooltip />
      </el-table>
    </ElFormItem>
    <StockSelect ref="stockSelect" />
  </ElForm>
</template>
<style lang="scss" scoped>
  .order {
    position: relative;
    >.el-form-item:not(.wf) {
      width: 49%;
    }
  }
</style>